package com.eqdd.yiqidian.ui.tongxunlu;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.arlib.floatingsearchview.FloatingSearchView;
import com.arlib.floatingsearchview.suggestions.model.SearchSuggestion;
import com.eqdd.yiqidian.AddFriendFirstTypeActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.StickyHeader1Custom;
import com.eqdd.yiqidian.adapter.recycleadapter.BaseQuickAdapter;
import com.eqdd.yiqidian.adapter.recycleadapter.BaseViewHolder;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.BaseBean;
import com.eqdd.yiqidian.bean.Person;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpPresneter;
import com.eqdd.yiqidian.ui.base.TextSuggestion;
import com.eqdd.yiqidian.utils.ContactsUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.adapter.PinItemDecoration;
import com.eqdd.yiqidian.widget.WaveSideBarView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by lvzhihao on 17-4-7.
 */

public class AddFriendFirstTypeActivity extends BaseActivity {


    private AddFriendFirstTypeActivityCustom dataBinding;
    private BaseQuickAdapter<Person, BaseViewHolder> quickAdapter;
    private ArrayList<Person> persons;
    private LinearLayoutManager mLinearLayoutManager;
    private boolean move;
    private ArrayList<TextSuggestion> searchSuggestions;


    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_add_friend_first_type);
    }

    @Override
    public void setView() {

        persons = new ArrayList<>();
        mLinearLayoutManager = new LinearLayoutManager(this);
        dataBinding.recyclerView.setLayoutManager(mLinearLayoutManager);
        dataBinding.recyclerView.addItemDecoration(new PinItemDecoration(this, new PinItemDecoration.DecorationCallback() {
            @Override
            public String getGroupLabel(int position) {
                System.out.println(position);
                if (position >= 0 && position < quickAdapter.getData().size()) {
                    return quickAdapter.getItem(position).getHeaderWord();
                }
                return null;
            }

            @Override
            public View getGroupView(int position) {
                StickyHeader1Custom inflate = DataBindingUtil.inflate(AddFriendFirstTypeActivity.this.getLayoutInflater(), R.layout.sticky_header_1, null, false);
                inflate.tvTitle.setText(quickAdapter.getItem(position).getHeaderWord());
                return inflate.getRoot();
            }
        }, 0));
        dataBinding.waveSideBar.setRecyclerView(dataBinding.recyclerView);
        if (quickAdapter == null) {
            quickAdapter = new BaseQuickAdapter<Person, BaseViewHolder>(R.layout.item_lianxiren, new ArrayList()) {
                @Override
                protected void convert(BaseViewHolder helper, Person item) {

                    helper.setText(R.id.tv_word, item.getHeaderWord())
                            .setText(R.id.tv_name, item.getName())
                            .setText(R.id.tv_phone, item.getPhone())
//                            .setImageBitmap(R.id.iv_icon_type, item.getPhoto())
                            .setVisible(R.id.iv_icon_type, false)
                            .setVisible(R.id.tv_add, false)
                            .setVisible(R.id.tv_word, false);
                }
            };
            dataBinding.recyclerView.setAdapter(quickAdapter);
            ItemClickSupport.addTo(dataBinding.recyclerView).setOnItemClickListener(
                    (rv, p, v) -> {
                        Intent intent = new Intent(AddFriendFirstTypeActivity.this,
                                FriendDetailInfoActivity.class);
                        intent.putExtra(Config.UNAME_OR_EQDCODE, quickAdapter.getItem(p).getPhone());
                        startActivity(intent);
                    }
            );
        }
        dataBinding.floatingSearchView.setOnQueryChangeListener((oldQuery, newQuery) -> {

                    if (TextUtils.isEmpty(newQuery)) {
                        ArrayList<Person> personTemp = new ArrayList<>();
                        personTemp.addAll(persons);
                        dataBinding.waveSideBar.setData(personTemp, new WaveSideBarView.OnLetterGet<Person>() {
                            @Override
                            public String letterGet(Person person) {
                                return person.getHeaderWord();
                            }
                        }, 0);
                        quickAdapter.notifyDataChanged(personTemp, true);
                    } else {
                        quickAdapter.notifyDataChanged(getNewPerson(newQuery), true);
                    }

                    TextSuggestion searchSuggestion = new TextSuggestion();
                    searchSuggestion.setBody(newQuery);
                    searchSuggestions = new ArrayList<>();
                    searchSuggestions.clear();
                    searchSuggestions.add(searchSuggestion);
                    dataBinding.floatingSearchView.swapSuggestions(searchSuggestions);
                }
        );
        dataBinding.floatingSearchView.setOnSearchListener(new FloatingSearchView.OnSearchListener() {
            @Override
            public void onSuggestionClicked(SearchSuggestion searchSuggestion) {
                enterInviteInfo(searchSuggestion.getBody());

            }

            @Override
            public void onSearchAction(String currentQuery) {
                enterInviteInfo(currentQuery);
            }
        });
    }

    private void enterInviteInfo(String phone) {
        Intent intent = new Intent(AddFriendFirstTypeActivity.this, FriendDetailInfoActivity.class);
        intent.putExtra(Config.UNAME_OR_EQDCODE, phone);
        startActivity(intent);
    }

    private void showInviteDialog(int position) {
        EditText editText = new EditText(this);
        editText.setHintTextColor(getResources().getColor(R.color.hint_color));
        editText.setText("我是" + user.getName());
        editText.setHint("请输入验证信息");
        AlertDialog show = new AlertDialog.Builder(this)
                .setTitle("发送好友请求")
                .setView(editText)
                .setPositiveButton("确定", (d, i) -> {
                    d.dismiss();
                    new HttpPresneter.Builder(HttpConfig.INVITE_FRIEND, BaseBean.class, AddFriendFirstTypeActivity.this)
                            .Params("userid", user.getUname())
                            .Params("friendid", quickAdapter.getItem(position).getPhone())
                            .Params("addcontent", "你好")
                            .setOnHttpListener(new HttpPresneter.OnHttpListener<BaseBean>() {
                                @Override
                                public void onError(Throwable e) {
                                    System.out.println(e.toString());

                                }

                                @Override
                                public void onNext(BaseBean baseBean) {
                                    ToastUtil.showShort(baseBean.getMsg());
                                    if (baseBean.getStatus() == 200) {

                                    }
                                    System.out.println(baseBean.toString());
                                }
                            })
                            .build()
                            .post();
                })
                .setNegativeButton("取消", (d, i) -> {
                    d.dismiss();
                }).show();
    }

    private List<Person> getNewPerson(String newText) {
        ArrayList<Person> newPersons = new ArrayList<>();
        for (int i = 0; i < persons.size(); i++) {
            if (persons.get(i).getPhone() != null && persons.get(i).getPhone().contains(newText) ||
                    persons.get(i).getName().contains(newText)) {
                newPersons.add(persons.get(i));
            }
        }
        //对集合排序
        Collections.sort(newPersons, new Comparator<Person>() {
            @Override
            public int compare(Person lhs, Person rhs) {
                //根据拼音进行排序
                return lhs.getPinyin().compareTo(rhs.getPinyin());
            }
        });
        dataBinding.waveSideBar.setData(newPersons, new WaveSideBarView.OnLetterGet<Person>() {
            @Override
            public String letterGet(Person person) {
                return person.getHeaderWord();
            }
        }, 0);
        return newPersons;

    }


    @Override
    public void initData() {
        initTopTitleBar(View.VISIBLE, "添加好友");
        showLoading();
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(final Subscriber<? super String> observer) {
                ArrayList<Person> allContacts = ContactsUtil.getMostQuickAllContacts(AddFriendFirstTypeActivity.this);
                persons.addAll(allContacts);
                //对集合排序
                Collections.sort(persons, new Comparator<Person>() {
                    @Override
                    public int compare(Person lhs, Person rhs) {
                        //根据拼音进行排序
                        return lhs.getPinyin().compareTo(rhs.getPinyin());
                    }
                });
                System.out.println(persons);
                observer.onNext("123");

            }
        })
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((o) -> {
                    ArrayList<Person> personTemp = new ArrayList<>();
                    personTemp.addAll(persons);
                    dataBinding.waveSideBar.setData(personTemp, new WaveSideBarView.OnLetterGet<Person>() {
                        @Override
                        public String letterGet(Person person) {
                            return person.getHeaderWord();
                        }
                    }, 0);
                    quickAdapter.notifyDataChanged(personTemp, true);
                    hideLoading();
                });

    }
}